package com.alexander.imgbannerwheelview;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoheihu
 * 改进需求：
 * 1：点击事件回调
 * 2：是否需要圆角的设置，以及圆角角度
 * 3：多种源数据类型，resourceId、bitmap、drawable、uri(url、path)
 */
public class ImgBannerWheelView extends LinearLayout implements LifeListener, ViewPager.OnPageChangeListener
{
    private static final String TAG = "ImgBannerWheelView";
    private ViewPager bannerViewpager;
    private LinearLayout indicatorLayout;
    private List<View> viewList = new ArrayList<>();
    private int[] imageIds;
    private List<ImageView> imageViewList = new ArrayList<>();
    private Integer[] indicatorImgs = new Integer[]{R.mipmap.icon_indicator_noselect, R.mipmap.icon_indicator_selected};
    private CountDownTimer countDownTimer;
    private int hostType = -1;
    private String hostFragmentTag;
    /**
     * 宿主类型ID
     */
    private final int[] HOSTTYPE = new int[]{0, 1};
    /**是否需要圆角*/
    private boolean needFillet = false;
    private float leftTopRoundAngle;
    private float leftBottomRoundAngle;
    private float rightTopRoundAngle;
    private float rightBottomRoundAngle;

    public ImgBannerWheelView(Context context) throws Exception
    {
        this(context, null);
    }

    public ImgBannerWheelView(Context context, AttributeSet attrs) throws Exception
    {
        this(context, attrs, 0);
    }

    public ImgBannerWheelView(Context context, AttributeSet attrs, int defStyleAttr) throws Exception
    {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public ImgBannerWheelView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
    {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onAttachedToWindow()
    {
        super.onAttachedToWindow();
        FragmentManager fragmentManager = null;
        Activity activity = getActivity();
        boolean alive = activity != null && !activity.isFinishing() && !activity.isDestroyed() && activity instanceof FragmentActivity;
        if(alive && hostType == HOSTTYPE[0])
        {
            fragmentManager = ((FragmentActivity)activity).getSupportFragmentManager();
        }
        else if(alive && hostType == HOSTTYPE[1])
        {
            fragmentManager = ((FragmentActivity)activity).getSupportFragmentManager();
            Fragment fragment = findFragmentByTag(hostFragmentTag, fragmentManager);
            if(fragment != null)
            {
                Log.e(TAG, "找到了");
                fragmentManager = fragment.getChildFragmentManager();
            }
            else
            {
                Log.e(TAG, getContext().getString(R.string.finderror));
                return;
            }
        }
        if(fragmentManager == null)
        {
            Log.e(TAG, getContext().getString(R.string.fragmentmanagererror));
            return;
        }
        LifeListenerFragment lifeListenerFragment = (LifeListenerFragment) fragmentManager.findFragmentByTag(TAG);
        if(lifeListenerFragment == null)
        {
            lifeListenerFragment = new LifeListenerFragment();
            fragmentManager.beginTransaction().add(lifeListenerFragment, TAG).commitAllowingStateLoss();
        }
        lifeListenerFragment.setLifeListener(this);
    }

    private Fragment findFragmentByTag(String tag, FragmentManager fragmentManager)
    {
        List<Fragment> fragments = fragmentManager.getFragments();
        if(fragments.size() > 0)
        {
            for (Fragment fragment : fragments)
            {
                if(fragment.getTag().equals(tag))
                {
                    return fragment;
                }
                else
                {
                    return findFragmentByTag(tag, fragment.getChildFragmentManager());
                }
            }
            return null;
        }
        else
        {
            return null;
        }
    }

    public void setImgs(int[] imgIds)
    {
        imageIds = imgIds;
        for (int i = 0; i < imageIds.length; i++)
        {
            /**添加图片*/
            View view1 = buildView(i);
            viewList.add(view1);
            /**添加指示器*/
            ImageView imageView = buildIndicator(i);
            indicatorLayout.addView(imageView);
            imageViewList.add(imageView);
        }
        bannerViewpager.setAdapter(new BannerPagerAdapter(viewList));
    }

    private void init(AttributeSet attrs) throws Exception
    {
        inflate(getContext(), R.layout.view_imgbannerwheel_layout, this);
        bannerViewpager = findViewById(R.id.banner_Viewpager);
        indicatorLayout = findViewById(R.id.indicator_Layout);
        bannerViewpager.addOnPageChangeListener(this);
        bannerViewpager.setOffscreenPageLimit(0);
        /**设置动画*/
        bannerViewpager.setPageTransformer(true, new AlphaTransformer());
        TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.host);
        hostType = array.getInt(R.styleable.host_hostType, -1);
        if (hostType < HOSTTYPE[0])
        {
            throw new Exception(getContext().getString(R.string.hosttypeerror));
        }
        if (hostType == HOSTTYPE[0])
        {
            hostFragmentTag = array.getString(R.styleable.host_fragmentTag);
            if (TextUtils.isEmpty(hostFragmentTag))
            {
                throw new Exception(getContext().getString(R.string.fragmenttagerror));
            }
        }
        needFillet = array.getBoolean(R.styleable.host_needFillet, false);
        if(needFillet)
        {
            leftTopRoundAngle = array.getDimension(R.styleable.host_left_top_round_angle, 0);
            rightTopRoundAngle = array.getDimension(R.styleable.host_right_top_round_angle, 0);
            rightBottomRoundAngle = array.getDimension(R.styleable.host_right_bottom_round_angle, 0);
            leftBottomRoundAngle = array.getDimension(R.styleable.host_left_bottom_round_angle, 0);
        }
        array.recycle();
    }

    /**
     * 构造图片view
     */
    private View buildView(int position)
    {
        View view = inflate(getContext(), R.layout.banneritem_layout, null);
        ImageView imageView = view.findViewById(R.id.imageView);
        imageView.setBackgroundResource(imageIds[position]);
        return view;
    }

    /**
     * 构造指示器图片
     */
    private ImageView buildIndicator(int position)
    {
        ImageView imageView = (ImageView) inflate(getContext(), R.layout.indicatoritem_layout, null);
        imageView.setImageResource(position == 0 ? indicatorImgs[1] : indicatorImgs[0]);
        return imageView;
    }

    /**
     * 设置指示器的选中状态
     */
    private void setIndicatorSelected(int position)
    {
        for (int i = 0; i < imageViewList.size(); i++)
        {
            imageViewList.get(i).setImageResource(position == i ? indicatorImgs[1] : indicatorImgs[0]);
        }
    }

    /**
     * 设置banner的自动轮播
     */
    private void setBannerAutoTranslation()
    {
        countDownTimer = new CountDownTimer(99999 * 1000, 3 * 1000)
        {
            @Override
            public void onTick(long millisUntilFinished)
            {
                int position = bannerViewpager.getCurrentItem();
                if (position == imageIds.length - 1)
                {
                    position = 0;
                } else
                {
                    position += 1;
                }
                bannerViewpager.setCurrentItem(position, true);
            }

            @Override
            public void onFinish()
            {
            }
        };
        new Handler(getContext().getMainLooper()).postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                countDownTimer.start();
            }
        }, (long) (2.8 * 1000));
    }

    private void destroyCountDowner()
    {
        countDownTimer.cancel();
        countDownTimer = null;
    }

    private Activity getActivity()
    {
        View parent = this;
        Activity activity = null;
        do
        {
            final Context context = parent.getContext();
            Log.d(TAG, "view: " + parent + ", context: " + context);
            if (context != null && context instanceof Activity)
            {
                activity = (Activity) context;
                break;
            }
        } while ((parent = (View) parent.getParent()) != null);
        return activity;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
    {

    }

    @Override
    public void onPageSelected(int position)
    {
        setIndicatorSelected(position);
    }

    @Override
    public void onPageScrollStateChanged(int state)
    {

    }


    @Override
    public void onCreate()
    {

    }

    @Override
    public void onStart()
    {

    }

    @Override
    public void onResume()
    {
        /**自动轮播*/
        setBannerAutoTranslation();
    }

    @Override
    public void onPause()
    {
        destroyCountDowner();
    }

    @Override
    public void onStop()
    {

    }

    @Override
    public void onDestroy()
    {

    }
}
